package javase.map;

import lombok.extern.slf4j.Slf4j;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;

@Slf4j
public class MapDemo {
    private MapDemo() {
    }
    private static Map<String, Object> currentHashMap = new ConcurrentHashMap<String, Object>();

    public static Map<String, Object> build(){
        if (currentHashMap.isEmpty()){
            synchronized (MapDemo.class){
                if (currentHashMap.isEmpty()){
                    currentHashMap = new ConcurrentHashMap<String, Object>(5);
                    log.info("currentHashMap.size()={}",currentHashMap.size());
                }
            }
        }
        return currentHashMap;
    }

    public static void main(String[] args) {
        System.out.println(1);

        //keySet如果直接add会报错:java.lang.UnsupportedOperationException
        //所以只能这样用
        Set<String> set = new HashSet<String>(MapDemo.build().keySet());
        set.add("first");
        set.add("second");
        set.add("third");
        log.info("keySet add res = {}",set.toString());

        ArrayList<String> strings = new ArrayList<String>(set);
        log.info("set={}",set.toString());

        /**
         * 最常见也是大多数情况下用的最多的，一般在键值对都需要使用
         */
        Map <String,String>map = new HashMap<String,String>();
        map.put("a", "1");
        map.put("b", "2");
        for(Map.Entry<String, String> entry : map.entrySet()){
            String mapKey = entry.getKey();
            String mapValue = entry.getValue();
            log.info("map.key={},map.value={}",mapKey,mapValue);
        }

        /**
         * 通过迭代器 遍历
         */
        Iterator<Map.Entry<String, String>> entries = map.entrySet().iterator();
        while(entries.hasNext()){
            Map.Entry<String, String> entry = entries.next();
            String key = entry.getKey();
            String value = entry.getValue();
            log.info("map.key={},map.value={}",key,value);
        }

        ArrayList<Map.Entry<Integer,String>> list = new ArrayList(map.entrySet());
        Collections.sort(list, (o1, o2) -> {
            return o1.getValue().compareTo(o2.getValue());//升序，前边加负号变为降序
        });
        log.info("list={}",list);
    }
}
